package cn.tedu.fruitshop.security;

import cn.tedu.fruitshop.mapper.UserMapper;
import cn.tedu.fruitshop.pojo.vo.UserLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * @author www
 * @create 2022-11-07 14:30
 */
@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("spring Security 框架自动调用UserDetailsServiceImpl中的LoadUserByUsername方法，参数：{}", s);
        UserLoginInfoVO userLoginInfoVO = userMapper.getLoginInfoByUsername(s);
        log.debug("{}",userLoginInfoVO);
        if (userLoginInfoVO == null) {
            log.debug("未找到用户名,即将抛出异常BadCredentialsException", s);
            String message = "登录失败，用户名不存在！";
            throw new BadCredentialsException(message);
        }
//        UserDetails userDetails = User.builder()
//                .username(loginInfoByUsername.getUsername())
//                .password(loginInfoByUsername.getPassword())
//                .disabled(loginInfoByUsername.getEnable() == 0)//是否禁用
//                .accountLocked(false)//未设计账号锁定的机制
//                .accountExpired(false)//未设置账号过期机制，
//                .credentialsExpired(false)//未设置凭证锁定机制
//                .authorities("暂时给出的假的权限标识")//权限
//                .build();
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        //遍历根据用户名查询到的管理员的权限
        for (String premission : userLoginInfoVO.getPremissions()) {
            //将查询到的权限赋予
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(premission);
            authorities.add(authority);
        }
        UserDetails userDetails = new UserDetails(
                userLoginInfoVO.getId(),
                userLoginInfoVO.getUsername(),
                userLoginInfoVO.getPassword(),
                userLoginInfoVO.getEnable() == 1,
                authorities
        );
        log.debug("即将向Spring Security框架返回UserDetails对象：{}", userDetails);
        return userDetails;
    }

}
